/* 
    "multer" // 上传文件
    "sqlite3"  // 链接数据库
    "uuid" // id
*/
const express = require("express");
const multer = require("multer");
const app = new express();
// const port = 8080;
const port = 80;
const path = require("path");
const { db } = require("./db/DbUtils");

// 开放跨域
app.use(function (req, res, next) {
  // 设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  // 允许的header类型
  res.header("Access-Control-Allow-Headers", "*");
  // 跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == "options")
    res.send(200); // 让options 尝试请求快速结束
  else next();
});

//  json使用
app.use(express.json());

// 上传功能
const update = multer({
  dest: "./public/upload/temp",
});

// 中间件
// category/_token/add
const ADMIN_TOKEN_PATH = "/_token";
const ShARE_TOKEN_PATH = "/_sharetoken";
app.all("*", async (req, res, next) => {
  if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {
    const { token } = req.headers;
    let admin_token_sql = "SELECT * FROM `admin` WHERE `token` = ?";
    let adminResult = await db.async.all(admin_token_sql, [token]);
    if (adminResult.err == !null || adminResult.rows.length == 0) {
      res.send({
        code: 403,
        msg: "请先登录",
      });
      return;
    } else {
      next();
    }
    // 开发token
  } else if (req.path.indexOf(ShARE_TOKEN_PATH) > -1) {
    const { token } = req.headers;
    let share_token_sql = "SELECT * FROM `share` WHERE `token` = ?";
    let shareResult = await db.async.all(share_token_sql, [token]);
    if (shareResult.err == !null || shareResult.rows.length == 0) {
      res.send({
        code: 403,
        msg: "请先登录",
      });
      return;
    } else {
      next();
    }
  } else {
    next();
  }
});

app.use(update.any());
app.use(express.static(path.join(__dirname, "public")));

app.use("/test", require("./routers/TestRouter"));
app.use("/admin", require("./routers/AdminRouter"));
app.use("/category", require("./routers/CategoryRouter"));
app.use("/blog", require("./routers/BlogRouter"));
app.use("/upload", require("./routers/UploadRouter"));
app.use("/share", require("./routers/ShareRouter"));

app.get("/", (req, res) => {
  res.send("hello world");
});

app.listen(port, () => {
  console.log(`启动成功：http://localhost:${port}/`);
});
